<template>
  <div id="app">
    <pages-header
        ref="pageHeader"
        :title="$route.params.id ? '编辑医生' : '添加医生' + doctorName"
        :backUrl="this.$routeProStr + '/medical/doctor_list'"
    >
    </pages-header>
    <div class="calender-class">
      <el-calendar v-model="calendarDate">
        <!-- 这里使用的是 2.5 slot 语法，对于新项目请使用 2.6 slot 语法-->
        <template slot="dateCell" slot-scope="{ date, data }">
          <div class="day-content-class">
            <template v-if="viewDate[data.day]">
              <div class="header-class">
                <div class="day-class">
                  {{ data.day.split("-").slice(1).join("-") }}
                </div>
                <div class="handle-class">
                  <el-button type="text" size="small" @click="handleAppointmentInfo(viewDate[data.day], data)">编辑
                  </el-button>
                </div>
              </div>
              <div class="paiban-class">
                <el-tag v-for="(dayValue, i) in viewDate[data.day]" type="warning">{{ dayValue }}</el-tag>
              </div>
            </template>
            <template v-else>
              <div class="header-class">
                <div class="day-class">
                  {{ data.day.split("-").slice(1).join("-") }}
                </div>
                <div class="handle-class">
                  <el-button type="text" size="small" @click="handleAppointmentInfo(viewDate[data.day], data)">编辑
                  </el-button>
                </div>
              </div>
              <div class="no-work-class">
                <div class="icon-class"><i class="el-icon-date"></i></div>
                <div class="tips-class">
                  暂无可预约时间
                </div>
              </div>
            </template>
          </div>
        </template>
      </el-calendar>
    </div>
    <!-- 单独预约 -->
    <div>
      <el-drawer :title="'【' + hanleDay.day + '】预约排期'" :visible.sync="drawer" size="40%">
        <div class="add-work-class">
          <el-form ref="form" :model="form" label-width="80px">
            <el-alert
                title="可预约时间（9点的意思是治疗时间是9点～9点30分）"
                type="warning"
                :closable="false"
                show-icon>
            </el-alert>
            <el-form-item label="可预约时间">
              <el-checkbox-group v-model="form.appointmentTime">
                <el-checkbox v-for="at in allowAppointmentTime" :label="at">{{ at }}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-form>
          <el-button class="add-btn-class" type="primary" @click="saveAppointment()">保存</el-button>
          <el-button class="add-btn-class" type="warning" @click="checkDefaultAppointmentTiem()">勾选默认时间
          </el-button>
        </div>
      </el-drawer>
    </div>
  </div>
</template>

<script>
import moment from "moment";
import {
  postDoctorAppointment, editDoctorAppointment, editMonthDoctorAppointment
} from '@/api/medical';

export default {
  data() {
    return {
      doctorId: 0,
      doctorName: "",
      viewDate: {},
      allowAppointmentTime: [
        "0:00", "0:30",
        "1:00", "1:30", "2:00", "2:30", "3:00", "3:30", "4:00", "4:30",
        "5:00", "5:30", "6:00", "6:30", "7:00", "7:30", "8:00", "8:30",
        "9:00", "9:30", "10:00", "10:30", "11:00", "11:30", "12:00", "12:30",
        "13:00", "13:30", "14:00", "14:30", "15:00", "15:30", "16:00", "16:30",
        "17:00", "17:30", "18:00", "18:30", "19:00", "19:30", "20:00", "20:30",
        "21:00", "21:30", "22:00", "22:30", "23:00", "23:30",
      ],
      form: {
        appointmentTime: []
      },
      thisDay: null,
      thisDayWork: null,
      ending: null,

      // 单日添加
      addForm: {
        appointmentTime: "甲",
        sort: 1,
      },
      drawer: false,
      innerDrawer: false,
      hanleDay: "",

      // 时间范围
      // dateRange: ['2023-12-1', '2023-12-20'],
      changeDateDrawer: false,
      // 点击月中已选中的日期
      currentDate: [],
      currentMonthStr: "",
      calendarDate: new Date(),
    };
  },
  created() {
    let id = this.$route.params.id;
    this.doctorId = id;
    this.currentMonthStr = this.$moment().format('YYYY-MM');
    this.postDoctorAppointmentList(id, this.currentMonthStr);
  },
  mounted() {
    let that = this;
    let nextBtn = document.querySelector(
        ".el-calendar__button-group .el-button-group>button:nth-child(3)"
    );
    let parent = nextBtn.parentNode;
    let button = document.createElement("button");
    button.type = "button";
    button.className = "primary el-button el-button--plain el-button--mini";
    button.textContent = "设置默认预约时间";
    button.addEventListener( 'click', () => {
      that.$confirm('确认设置当月【' +that.currentMonthStr+ '】所有日期默认预约时间吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        beforeClose(action, instance, done) {
          if (action == 'confirm') {
            editMonthDoctorAppointment( that.doctorId, {
              appointment_month: that.currentMonthStr,
              appointment_times: [
                "9:00", "9:30", "10:00", "10:30", "11:00", "11:30",
                "14:00", "14:30", "15:00", "15:30", "16:00", "16:30",
                "17:00", "17:30",
              ],
            }).then((res) => {
              that.$message.success(res.msg);
              that.postDoctorAppointmentList(that.doctorId, that.currentMonthStr);
              done();
            })
                .catch((res) => {
                  this.drawer = false;
                  this.$message.error(res.msg)
                })
          } else {
            done();
          }
        },
      })
          .catch(() => {});
    });
    parent.appendChild(button);
  },
  watch: {
    calendarDate(val, oldVal) {
      this.currentMonthStr = moment(val).format("YYYY-MM");
    }
  },
  computed: {},
  methods: {
    // 获取医生预约时间列表；
    postDoctorAppointmentList(id, month) {
      this.loading = true;
      postDoctorAppointment(id, {
        month: month
      })
          .then((res) => {
            let data = res.data;
            this.doctorName = data.doctor_info.name
            this.viewDate = data.appointment_list;
            this.loading = false;
          })
          .catch((res) => {
            this.loading = false;
            this.$message.error(res.msg);
          });
    },

    // 编辑单日预约
    handleAppointmentInfo(info, data) {
      this.hanleDay = data;
      this.drawer = true;
      if (info && info.length > 0) {
        this.form.appointmentTime = info;
      } else {
        this.form.appointmentTime = [];
      }
    },
    handleClose() {
      this.innerDrawer = false;
    },
    // 添加单日预约
    saveAppointment() {
      console.log('save_app');
      let appointmentTime = this.form.appointmentTime;
      editDoctorAppointment(this.doctorId, {
        appointment_date: this.hanleDay.day,
        appointment_times: appointmentTime,
      }).then((res) => {
        this.$message.success(res.msg);
        this.form.appointmentTime = appointmentTime;
        this.$set(this.viewDate, this.hanleDay.day, this.form.appointmentTime);
        this.drawer = false;
        if (appointmentTime.length === 0) {
          this.$delete(this.viewDate, this.hanleDay.day);
        }
      })
          .catch((res) => {
            this.drawer = false;
            this.$message.error(res.msg)
          })

    },
    // 勾选默认时间
    checkDefaultAppointmentTiem() {
      this.form.appointmentTime = [
        "9:00", "9:30", "10:00", "10:30", "11:00", "11:30",
        "14:00", "14:30", "15:00", "15:30", "16:00", "16:30",
        "17:00", "17:30",
      ];
      this.$set(this.viewDate, this.hanleDay.day, this.form.appointmentTime);
    },
  },
};
</script>

<style>
#app {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}

.el-table__fixed-right {
  height: 100% !important;
}

.calender-class {
  width: 100%;
  height: 100%;
}

.is-selected {
  color: #1989fa;
}

.el-calendar-table {
  height: 100%;
}

.el-calendar-day {
  height: 100% !important;
}

.day-content-class {
  display: flex;
  flex-direction: column;
}

.header-class {
  flex: 1;
  display: flex;
  height: 28px;
  flex-direction: row;
  justify-content: space-between;
}

.day-class {
  flex: 4;
  line-height: 32px;
  margin-left: 10px;
}

.handle-class {
  flex: 1;
}

.paiban-class {
  flex: 4;
  display: flex;
  vertical-align: middle;
  text-align: center;
  flex-wrap: wrap;
  flex-direction: row;
  justify-content: center;
  align-items: flex-end;
}


.el-tag {
  margin-right: 5px;
  margin-bottom: 5px;
  display: flex;
  width: auto!important;
}

.no-work-class {
  text-align: center;
  color: #cacaca;
}

.icon-class {
  font-size: 20px;
  margin-bottom: 20px;
}

/* 侧边弹窗 */
.add-btn-class {
  margin: 10px;
  float: right;
}


.change-date-drawer-class .day-content-class {
  height: 30px
}

.disabled-date-class {
  color: #ccc;
  pointer-events: none;
}

.el-tag {
  width: 30px;
  text-align: center;
  display: block;
}
</style>